package client.comm.baoding.fragment

import android.content.Intent
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.children
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.utils.Util
import client.comm.baoding.R
import client.comm.baoding.adapter.CatePagingAdapter
import client.comm.baoding.adapter.main.CateAllCateAdapter
import client.comm.baoding.adapter.main.CateShowAdapter
import client.comm.baoding.adapter.page.CateGoodsPageAdapter
import client.comm.baoding.databinding.CateChildTagBinding
import client.comm.baoding.databinding.FragmentTabtwoBinding
import client.comm.baoding.databinding.LayoutCatetabItemBinding
import client.comm.baoding.ui.SearchActivity
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.commlib.base.PagerFooterAdapter
import client.comm.commlib.comm_ui.draw.SpaceGridItemDecoration
import client.comm.commlib.comm_ui.draw.SpaceItemBottomWhiteDecoration
import client.comm.commlib.dipToPx
import client.comm.commlib.network.data.PagingJsonResult
import client.comm.commlib.toast.toast
import client.comm.commlib.widget.EmptyLayout
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class TabTwoFragment : BaseFragment<FragmentTabtwoBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabtwo
    }


    val adapter: CatePagingAdapter by lazy {
        CatePagingAdapter(requireContext(), mImgLoader).apply {
            refreshLoading = {
                if (itemCount == 0) {
                    binding.emptyGoodsLayout.errorType = EmptyLayout.NETWORK_LOADING
                }
            }
            refreshNotLoading = {
                if (itemCount == 0) {
                    binding.emptyGoodsLayout.errorType = EmptyLayout.NODATA
                } else {
                    binding.emptyGoodsLayout.visibility = View.GONE
                }
            }
            refreshError = {
                if (itemCount == 0)
                    binding.emptyGoodsLayout.errorType = EmptyLayout.NETWORK_ERROR
                toast((it).error.message)
            }
            appendError = {
            }
        }
    }
    val jyCateAdapter: CateShowAdapter by lazy {
        CateShowAdapter(requireContext(), mImgLoader).apply {
            cateCli = { it, p ->
                viewModel.currGoodsCateId.value = it.category_id
                viewModel.isThreeLeveReq.value = true
                adapter.refresh()
                viewModel.curThreeTabIndex.value = p

                for ((i, c) in binding.cateScrollWrap.children.withIndex()) {
                    val t = c.findViewById<TextView>(R.id.txt)
                    if (i == p) {
                        t.isSelected = true
                    } else {
                        t.isSelected = false
                    }
                }

                closeCate()
            }
        }
    }

    override fun initViewModel(): MainViewModel = createViewModel()


    override fun initWidget() {
        binding.statusBar.post {
            val h = Util.getStatusBarHeight(requireContext())
            val p = binding.statusBar.layoutParams
            p.height = h
            binding.statusBar.layoutParams = p
            Util.setBg(resources!!.getColor(R.color.white), requireActivity().window)
            val controller = ViewCompat.getWindowInsetsController(binding.root)
            controller?.isAppearanceLightStatusBars = true
        }

        binding.recyclerView.adapter = adapter.withLoadStateFooter(PagerFooterAdapter())
        binding.recyclerView.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

        binding.recyclerView.addItemDecoration(
            SpaceGridItemDecoration(dipToPx(resources, 5.0f).toInt(), false)
        )

        binding.emptyGoodsLayout.setOnClickListener {
            adapter.refresh()
        }

        binding.tabCateParent.clearOnTabSelectedListeners()
        binding.tabCateParent.addOnTabSelectedListener(object :
            TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let {
                    viewModel.cutOneTabId.value = "${it.tag}"
                    viewModel.cutTwoTab.value = null
                    initTwoTabs()

                    viewModel.currGoodsCateId.value = ""
                    viewModel.cutTwoTab.value?.let {
                        viewModel.currGoodsCateId.value =
                            "${it.category_id}"
                    }

                    viewModel.isThreeLeveReq.value = false

                    if (viewModel.isInitLauncherCate.value!!) {
                        adapter.refresh()
                    } else
                        getGoodsByCate()
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
        binding.cateRecycler.layoutManager = GridLayoutManager(requireContext(), 3)
        binding.cateRecycler.addItemDecoration(
            SpaceGridItemDecoration(
                TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, 10.0f, requireContext().resources.displayMetrics
                ).toInt()
            )
        )
        binding.cateRecycler.adapter = jyCateAdapter

        viewModel.callCate.observe(this, {
            it?.let {
                if (it.isSuccess) {

                    it.data?.let {
                        binding.emptyLayout.visibility = View.GONE

                        it.category_list.let {
                            binding.tabCateParent.removeAllTabs()

                            var inx = 0
                            for ((i, s) in it.withIndex()) {
                                val tab = binding.tabCateParent.newTab().apply {
                                    tag = s.category_id
                                    setText(s.name)
                                }

                                if (i == 0 && viewModel.cutOneTabId.value.isNullOrEmpty()) {
                                    viewModel.cutOneTabId.value = "${s.category_id}"
                                }

                                val b = viewModel.cutOneTabId.value.equals("${s.category_id}")

                                binding.tabCateParent.addTab(
                                    tab,
                                    b
                                )

                                if (b)
                                    inx = i
                            }
                            binding.tabCateParent.postDelayed({
                                binding.tabCateParent.setScrollPosition(inx, 0.0f, false)
                            }, 50)

                        }

                    }
                } else {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })

        binding.emptyLayout.setOnClickListener {
            viewModel.holdCate()
        }
        binding.event = this

    }

    fun getGoodsByCate() {
        viewModel.isInitLauncherCate.value = true
        closeCate()
        viewModel.viewModelScope.launch {
            viewModel.pagingDataAuto(20, hold = {

                if (!viewModel.currGoodsCateId.value.isNullOrEmpty()) {
                    var ret = viewModel.server.goods_type_detail(
                        it,
                        "${viewModel.currGoodsCateId.value}"
                    ).body()

                    if (it == 1 && !viewModel.isThreeLeveReq.value!!) {
                        withContext(Dispatchers.Main) {
                            jyCateAdapter.submitList(ret?.data?.category_list)
                            ret?.data?.category_list?.let {
                                binding.cateScrollWrap.removeAllViews()
                                for ((i, s) in it.withIndex()) {
                                    DataBindingUtil.inflate<CateChildTagBinding>(
                                        layoutInflater,
                                        R.layout.cate_child_tag,
                                        binding.tabContent,
                                        false
                                    ).apply {

                                        bean = s
                                        currIndex = i

                                        txt.isSelected =
                                            viewModel.curThreeTabIndex.value == (currIndex)
                                        txt.setOnClickListener {
                                            viewModel.curThreeTabIndex.value = (currIndex)
                                            viewModel.currGoodsCateId.value = s.category_id
                                            for (c in binding.cateScrollWrap.children) {
                                                val t = c.findViewById<TextView>(R.id.txt)
                                                if (t.isSelected) {
                                                    t.isSelected = false
                                                    break
                                                }
                                            }
                                            txt.isSelected = true
                                            jyCateAdapter.currIndex = i
                                            jyCateAdapter.notifyDataSetChanged()
                                            viewModel.isThreeLeveReq.value = true
                                            adapter.refresh()
                                        }
                                        binding.cateScrollWrap.addView(root)
                                    }
                                }
                            }
                        }

                    }
                    PagingJsonResult(
                        list = ret?.data?.goods_list,
                        code = ret?.code,
                        message = ret?.message
                    )
                } else {
                    PagingJsonResult(
                        list = arrayListOf(),
                        code = 200,
                        message = ""
                    )
                }

            }).collect {
                adapter.submitData(it)
            }
        }
    }

    fun initTwoTabs() {
        viewModel.callCate.value?.data?.let {

            val curId = viewModel.cutOneTabId.value

            for (s in it.category_list) {

                if ("${s.category_id}".equals(curId)) {
                    binding.tabContent.removeAllViews()
                    binding.cateScrollWrap.removeAllViews()
                    jyCateAdapter.submitList(null)
                    for ((i, s) in s.sub_list.withIndex()) {
                        if (i == 0 && viewModel.cutTwoTab.value == null) {
                            viewModel.cutTwoTab.value = s
                            viewModel.cutTwoTabIndex.value = i
                            viewModel.curThreeTabIndex.value = i
                        }
                        DataBindingUtil.inflate<LayoutCatetabItemBinding>(
                            layoutInflater,
                            R.layout.layout_catetab_item,
                            binding.tabContent,
                            false
                        ).apply {
                            root.isSelected =
                                viewModel.cutTwoTab.value?.category_id == s.category_id

                            vVerticalLine.setBackgroundColor(
                                resources.getColor(if (viewModel.cutTwoTab.value?.category_id == s.category_id) R.color.main_color else R.color.tranplant)
                            )
                            txtTv.text = "${s.name}"
                            binding.tabContent.addView(root)

                            root.setOnClickListener {
                                if (s.category_id == viewModel.cutTwoTab.value?.category_id) {
                                    return@setOnClickListener
                                }

                                val oldView =
                                    binding.tabContent.getChildAt(viewModel.cutTwoTabIndex.value!!)
                                oldView.isSelected = false
                                oldView.findViewById<View>(R.id.v_vertical_line).setBackgroundColor(
                                    resources.getColor(R.color.tranplant)
                                )
                                viewModel.cutTwoTabIndex.value = i
                                viewModel.cutTwoTab.value = s
                                root.isSelected = true
                                vVerticalLine.setBackgroundColor(
                                    resources.getColor(R.color.main_color)
                                )
                                viewModel.isThreeLeveReq.value = true
                                viewModel.currGoodsCateId.value = "${s.category_id}"

                                adapter.refresh()
                            }
                        }

                    }
                }
            }
            // 二级分类变化

        }

    }

    override fun initData() {
        viewModel.isInitLauncherCate.value = false
        viewModel.holdCate()
    }

    private var popupWindow: PopupWindow? = null
    val cateAllAdapter: CateAllCateAdapter by lazy {
        CateAllCateAdapter(requireContext(), mImgLoader).apply {

            cateItemCli = { it, p ->
                popupWindow?.dismiss()
                val tab = binding.tabCateParent.getTabAt(p)
                binding.tabCateParent.selectTab(tab)
            }
        }
    }

    fun showAllCate() {
        if (popupWindow == null) {
            val view = layoutInflater.inflate(R.layout.all_cate_popup_layout, null)


            val recyclerViewCate = view.findViewById<RecyclerView>(R.id.recyclerViewCate)
            view.findViewById<View>(R.id.closeBtn).apply {
                setOnClickListener {
                    popupWindow?.dismiss()
                }
            }
            view.findViewById<View>(R.id.coverBtn).apply {
                setOnClickListener {
                    popupWindow?.dismiss()
                }
            }
            recyclerViewCate.layoutManager = GridLayoutManager(requireContext(), 5)
            recyclerViewCate.addItemDecoration(
                SpaceGridItemDecoration(
                    TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP,
                        0.1f,
                        requireContext().resources.displayMetrics
                    ).toInt()
                )
            )
            recyclerViewCate.adapter = cateAllAdapter
            // 在此处设置弹窗内部的布局和监听器等

            popupWindow = PopupWindow(
                view,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
            )
//        popupWindow?.animationStyle = R.style.PopupAnimation
//            popupWindow?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            popupWindow?.isOutsideTouchable = true
        }

        viewModel.callCate.value?.data?.let {
            cateAllAdapter.submitList(it.category_list)
        }

        // 显示在 anchorView 的下方
        popupWindow?.showAsDropDown(binding.titleWrap)
    }

    fun switchCate() {
        when (binding.coverView.visibility) {
            View.VISIBLE -> {
                binding.arrowImg.setImageResource(R.mipmap.ic_arrow_bottom)
                binding.coverView.visibility = View.GONE
            }

            else -> {
                binding.arrowImg.setImageResource(R.mipmap.ic_arrow_top)
                binding.coverView.visibility = View.VISIBLE
            }
        }
    }

    fun closeCate() {
        binding.arrowImg.setImageResource(R.mipmap.ic_arrow_bottom)
        binding.coverView.visibility = View.GONE
    }

    fun goSearch() {
        startActivity(Intent(requireContext(), SearchActivity::class.java))
    }
}